<template>
    <van-nav-bar :title="`${route.name === 'second_add' ? '添加' : '编辑'}系列`" left-text="返回" left-arrow @click-left="$router.back()"></van-nav-bar>
    <div class="content">
        <!-- 表单 -->
         <van-form @submit="submitForm">
            <van-cell-group inset>
                <van-field v-model="formData.name" name="name" label="名称" :rules="[{ required: true, message: '请输入系列名称'}]"></van-field>
            </van-cell-group>
            <div class="button-container">
                <van-button style="width: 100%;" type="primary" native-type="submit">保存</van-button>
            </div>
         </van-form>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { http } from '../../utils/request'
const route = useRoute()
const router = useRouter()

const formData = reactive({
    name: '',
})
const data = ref({})

const submitForm = () => {
    if(route.name === 'second_add') {
        // 新增
        const postData = {
            name: formData.name,
            parentId: route.query.parentId,
            level: 1
        }
        http.post('/category/saveOrUpdate', postData).then(res => {
            showToast('保存成功')
            router.back()
        })
    } else {
        // 修改
        const postData = {
            id: route.query.id,
            name: formData.name,
            parentId: route.query.parentId,
            level: 1
        }
        http.post('/category/saveOrUpdate', postData).then(res => {
            showToast('保存成功')
            router.back()
        })
    }
}

const editInit = () => {
    http.get('/category/getOne?id=' + route.query.id).then(res => {
        formData.name = res.name
    })
}

onMounted(() => {
    if(route.name ==='second_edit') {
        editInit()
    }
})
</script>
<style lang="scss" scoped>
.content {
    background-color: #f7f8fa;
    min-height: calc(100vh - 46px);
    padding: 10px;
}

.button-container {
    padding: 0 20px;
}
</style>